package cn.com.fuhuitong.utils

import android.annotation.SuppressLint
import android.os.Build
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.annotation.RequiresApi
import cn.com.fuhuitong.app.BASE_HTTP_URL
import com.blankj.utilcode.util.LogUtils
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements

@SuppressLint("SetJavaScriptEnabled,JavascriptInterface")
object WebViewUtils {
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun initWebView(webView: WebView) {
        with(webView) {
            settings.javaScriptEnabled = true
            settings.useWideViewPort = true
            settings.loadWithOverviewMode = true
            settings.setSupportZoom(false)
//            settings.minimumFontSize = ScreenUtil.dip(context, 14)
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
    }

    fun loadFullScreenHtml(webView: WebView, content: String) {
        val document: Document = Jsoup.parse(content)
        val elements: Elements = document.select("img")
        elements.forEach {
            val url = "$BASE_HTTP_URL${it.attr("src")}"
            val style = "${it.attr("style")}width:100%;"
            it.attr("src", url)
            it.attr("style", style)
        }
        val realContent = buildString {
            append("<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>img,#content{width:100%} img{display: block;}*{margin:0;padding: 0}</style></head><body>")
            append(document.body().toString()).append("<p><br/></p>")
            append("</body></html>")
        }
        webView.loadDataWithBaseURL("", realContent, "text/html", "utf-8", null)
    }

    fun addWebView2Container(webView: WebView, container: FrameLayout) {
        webView.overScrollMode = View.OVER_SCROLL_NEVER
        container.addView(
            webView,
            FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
        )
    }

    fun removeWebView(webView: WebView, container: FrameLayout) {
        container.removeAllViews()
        webView.stopLoading()
        webView.clearHistory()
        webView.destroy()
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun WebView.init() {
        settings.javaScriptEnabled = true
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.setSupportZoom(false)
//        settings.minimumFontSize = ScreenUtil.dip(context, 28)
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
    }

    fun WebView.addImageClickListener(onClick: (src: String?) -> Unit) {
        this.addJavascriptInterface(object : JavaScriptInterface {
            @JavascriptInterface
            override fun openImage(src: String?) {
                onClick(src)
            }
        }, "imageClick")
        this.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                settings.javaScriptEnabled = true
                super.onPageFinished(view, url)
                loadUrl(
                    "javascript:(function(){" +
                            "var imgs=document.getElementsByTagName(\"img\");" +
                            "for(var i=0;i<imgs.length;i++){" +
                            "imgs[i].onclick=function(){" +
                            "window.imageClick.openImage(this.src);" +
                            "}}})()"
                )
            }
        }
    }
}

interface JavaScriptInterface {
    @JavascriptInterface
    fun openImage(src: String?)
}